package com.atguigu.tingshu.user.init;

import jakarta.annotation.PostConstruct;
import jakarta.annotation.Resource;
import lombok.extern.log4j.Log4j;
import lombok.extern.log4j.Log4j2;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.core.ReturnedMessage;
import org.springframework.amqp.rabbit.connection.CorrelationData;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.stereotype.Component;

/***
 * RAbbitMq可靠投递
 */
@Component
@Log4j2
public class RabbitConfirmAndReturninit implements RabbitTemplate.ConfirmCallback,RabbitTemplate.ReturnsCallback {
    @Resource
    RabbitTemplate rabbitTemplate;
    @PostConstruct
    public void init(){
        rabbitTemplate.setMandatory(true);
        rabbitTemplate.setConfirmCallback(this::confirm);
        rabbitTemplate.setReturnsCallback(this::returnedMessage);
    }

    /**
     * confirm
     * @param correlationData 记录消息编号，确认是否反复发送
     * @param b 是否抵达交换机
     * @param s 没有抵达报错
     */

    @Override
    public void confirm(CorrelationData correlationData, boolean b, String s) {
        if(!b){
            //记录消息到日志
            log.error("消息没豆抵达交换机失败原因"+s);
        }
    }

    /**
     * returnMessage
     * @param returnedMessage
     */
    @Override
    public void returnedMessage(ReturnedMessage returnedMessage) {
        //错误码
        int replyCode = returnedMessage.getReplyCode();
        //错误内容
        String replyText = returnedMessage.getReplyText();
        //交换机
        String exchange = returnedMessage.getExchange();
        //routingKey
        String routingKey = returnedMessage.getRoutingKey();
        //message
        Message message = returnedMessage.getMessage();
        log.error("消息抵达交换机，但是没有抵达队列，失败错误码：{}，"+
                "原因为{},"+
                "交换机为：{},"+
                "routingKey为{}"+
                "消息内容为{}",
                replyCode,replyText,exchange,routingKey,new String(message.getBody()));
    }
}
